import os
import json
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QHBoxLayout
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QFont, QPixmap
from qfluentwidgets import SmoothScrollArea, PrimaryPushButton, InfoBar, InfoBarPosition
from visualize import Animation3D


class HoverMoveButton(PrimaryPushButton):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.original_pos = self.pos()
        self.move_offset = QPoint(5, 5)  # 向右下角移动的偏移量

    def enterEvent(self, event):
        self.original_pos = self.pos()
        self.move(self.pos() + self.move_offset)
        super().enterEvent(event)

    def leaveEvent(self, event):
        self.move(self.original_pos)
        super().leaveEvent(event)


class AnimationInterface(SmoothScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.view = QWidget(self)
        self.vBoxLayout = QVBoxLayout(self.view)
        self.setWidget(self.view)
        self.setWidgetResizable(True)

        # 将背景样式直接应用到主视图
        self.view.setStyleSheet('''
            QWidget#mainView {
                border-image: url(pic/background2.png) 0 0 0 0 stretch stretch;
            }
        ''')
        self.view.setObjectName("mainView")

        # 添加中间层图片
        self.bg_image = QLabel(self.view)
        self.bg_image.setPixmap(QPixmap("pic/pic3ddonghua.png"))
        self.bg_image.setScaledContents(True)  # 允许图片缩放
        self.bg_image.setStyleSheet('background: transparent;')
        self.bg_image.lower()  # 将图片置于底层，但在背景之上

        # 确保滚动区域和其他组件保持透明
        self.setStyleSheet('''
            QScrollArea {
                border: none;
                background: transparent;
            }
            QLabel {
                background: transparent;
                color: white;
            }
            QPushButton {
                border: none;
                background-color: transparent;
            }
        ''')

        self.animation_window = None
        self.initUI()

    def initUI(self):
        self.vBoxLayout.setAlignment(Qt.AlignCenter)
        self.vBoxLayout.setSpacing(60)  # 增大控件间距

        # 增加顶部空白，将整体内容向下移动40%
        self.vBoxLayout.addSpacing(400)  # 原来是150，增加到400

        # 删除标题相关代码

        # 添加说明文本
        description = QLabel('本功能将展示路径规划的3D动画效果\n请确保已完成路径规划步骤')
        description.setFont(QFont("Microsoft YaHei", 14))
        description.setAlignment(Qt.AlignCenter)
        self.vBoxLayout.addWidget(description)

        # 增加说明文本和状态标签之间的间距
        self.vBoxLayout.addSpacing(60)

        # 添加状态标签
        self.status_label = QLabel('准备就绪...')
        self.status_label.setFont(QFont("Microsoft YaHei", 14))
        self.status_label.setAlignment(Qt.AlignCenter)
        self.vBoxLayout.addWidget(self.status_label)

        # 增加状态标签和按钮之间的间距
        self.vBoxLayout.addSpacing(150)

        # 创建水平布局来居中放置按钮
        button_layout = QHBoxLayout()
        button_layout.setAlignment(Qt.AlignCenter)

        # 修改播放按钮样式使用背景图片
        self.play_button = HoverMoveButton('')  # 使用自定义的悬停移动按钮
        pixmap = QPixmap("pic/bofangdonghua.png")
        self.play_button.setFixedSize(pixmap.size())  # 设置按钮大小与图片一致
        self.play_button.setStyleSheet('''
            PrimaryPushButton {
                border: none;
                background-image: url(pic/bofangdonghua.png);
                background-position: center;
                background-repeat: no-repeat;
                background-color: transparent;
            }
            PrimaryPushButton:hover {
                background-color: transparent;
            }
            PrimaryPushButton:pressed {
                background-color: transparent;
            }
        ''')
        self.play_button.clicked.connect(self.show_animation)
        button_layout.addWidget(self.play_button)

        self.vBoxLayout.addLayout(button_layout)

        # 添加底部弹性空间
        self.vBoxLayout.addStretch()

    def load_data(self):
        """加载路径规划结果和地图数据"""
        try:
            current_dir = os.path.dirname(os.path.abspath(__file__))
            data_dir = os.path.join(current_dir, "data")

            maps = []
            starts = []
            goals = []
            paths = []

            valid_data_found = False

            # 读取每个象限的动画数据
            for i in range(1, 5):
                animation_file = os.path.join(data_dir, f"quadrant_{i}.animation.json")
                quadrant_data = []

                if os.path.exists(animation_file):
                    try:
                        with open(animation_file, 'r', encoding='utf-8') as f:
                            data = json.load(f)

                        # 转换数据格式
                        map_data = [[bool(cell) for cell in row] for row in data['map']]
                        start_data = [tuple(s) for s in data['starts']]
                        goal_data = [tuple(g) for g in data['goals']]
                        path_data = [[tuple(p) for p in path] for path in data['paths']]

                        maps.append(map_data)
                        starts.append(start_data)
                        goals.append(goal_data)
                        paths.append(path_data)
                        valid_data_found = True
                    except Exception as e:
                        print(f"读取象限 {i} 数据时出错: {str(e)}")
                        maps.append([])
                        starts.append([])
                        goals.append([])
                        paths.append([])
                else:
                    maps.append([])
                    starts.append([])
                    goals.append([])
                    paths.append([])

            if not valid_data_found:
                raise Exception("没有找到有效的地图数据")

            return maps, starts, goals, paths

        except Exception as e:
            raise Exception(f"加载数据时出错: {str(e)}")

    def show_animation(self):
        """显示3D动画"""
        try:
            # 如果已经存在动画窗口，先关闭并清理
            if self.animation_window:
                self.animation_window.close()
                self.animation_window.deleteLater()
                self.animation_window = None

            self.status_label.setText('正在加载动画...')
            self.play_button.setEnabled(False)

            # 加载并显示动画
            maps, starts, goals, paths = self.load_data()
            self.animation_window = Animation3D(maps, starts, goals, paths)

            # 连接关闭信号以进行清理
            self.animation_window.destroyed.connect(self.on_animation_closed)
            self.animation_window.show()

            self.status_label.setText('动画窗口已打开')
            InfoBar.success(
                title='成功',
                content='动画窗口已打开',
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=2000,
                parent=self
            )

        except Exception as e:
            self.status_label.setText('播放失败')
            InfoBar.error(
                title='错误',
                content=f'动画播放出错: {str(e)}',
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=4000,
                parent=self
            )
        finally:
            self.play_button.setEnabled(True)

    def on_animation_closed(self):
        """动画窗口关闭时的清理函数"""
        if self.animation_window:
            self.animation_window = None

    def closeEvent(self, event):
        """界面关闭时的清理"""
        if self.animation_window:
            self.animation_window.close()
            self.animation_window.deleteLater()
            self.animation_window = None
        super().closeEvent(event)

    def resizeEvent(self, event):
        """重写调整大小事件以确保图片始终填满界面"""
        super().resizeEvent(event)
        self.bg_image.setGeometry(0, 0, self.view.width(), self.view.height())
